package hhtc.jsjds.service.impl;

import hhtc.jsjds.entity.User;
import hhtc.jsjds.enums.StatusCodeEnum;
import hhtc.jsjds.exception.XscoderException;
import hhtc.jsjds.mapper.RaterMapper;
import hhtc.jsjds.service.SysAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SysAdminServiceImpl implements SysAdminService {

    @Autowired
    RaterMapper raterMapper;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    @Transactional
    public User addNewRate(User user, Integer[] categories) {
        user.setPassword(passwordEncoder().encode(user.getPassword()));
        try{
            raterMapper.addNewRater(user);
            raterMapper.add2Role(user);
            for (int i = 0; i < categories.length; i++) {
                raterMapper.add2RaterToCategory(user.getId(), categories[i] + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new XscoderException(StatusCodeEnum.OPT_FAILD);
        }
        return user;
    }

    @Override
    public User addFinalSeqAccount(User user, Integer[] categoriesSelect) {
        user.setPassword(passwordEncoder().encode(user.getPassword()));
        try {
            raterMapper.addNewRater(user);
            raterMapper.addFinalSeqAccount(user);
            List<Integer> areaIds = raterMapper.getAllAreaId(Arrays.asList(categoriesSelect));
            for (Integer areaId : areaIds) {
                raterMapper.addFinalAccountCategory(user.getId(), areaId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new XscoderException(StatusCodeEnum.OPT_FAILD);
        }
        return user;
    }
}
